import re
import json
import time
import requests

class Email:
    "bccto.me 操作类"

    # 邮箱地址
    email = None
    # 全局Cookie
    cookies = None

    # 初始化
    def init(self, address):
        self.cookies = requests.get(
            "http://www.bccto.me/",
            headers={
                "Accept-Language": "zh-CN,zh;q=0.8,en;q=0.6"
            }
        ).cookies

        return self.apply(address)

    # 申请邮箱
    def apply(self, address):
        req = requests.post(
            "http://www.bccto.me/applymail",
            data={
                "mail": address
            },
            headers={
                "Accept": "application/json, text/javascript, */*; q=0.01",
                "Accept-Language": "zh-CN,zh;q=0.8,en;q=0.6",
                "Referer": "http://www.bccto.me/",
                "X-Requested-With": "XMLHttpRequest"
            },
            cookies=self.cookies
        )

        if json.loads(req.text)["success"] == "true":
            self.email   = address
            self.cookies = req.cookies
            return True
        else:
            return False

    # 检查邮件
    def watch(self):
        req = requests.post(
            "http://www.bccto.me/getmail",
            data={
                "mail": self.email,
                "time": int(time.time() - 8)
            },
            cookies=self.cookies,
            headers={
                "Accept-Language": "zh-CN,zh;q=0.8,en;q=0.6",
                "Referer": "http://www.bccto.me/",
                "X-Requested-With": "XMLHttpRequest"
            }
        )

        arr = []
        obj = json.loads(req.text)
        for x in obj["mail"]:
            arr.append(x[4])

        return arr

    # 读取邮件
    def read(self, pid):
        html = requests.get(
            self.replace(pid),
            cookies=self.cookies,
            headers={"Accept-Language": "zh-CN,zh;q=0.8,en;q=0.6"}
        ).text
        return re.findall(r'</script><br/><hr/><br/><div dir="ltr">(.*?)(?:<br>)?</div>', html)[0]

    # 替换邮件地址
    def replace(self, pid):
        email = self.email.replace("@", "(a)").replace(".", "-_-")
        return "http://www.bccto.me/win/%s/%s" % (email, pid)

